<template>
  <div class="industry-data-management tech-page">
    <dv-border-box-12 class="tech-header-box">
      <div class="tech-header">
        <h2 class="tech-title">行业数据管理</h2>
        <el-button type="primary" class="tech-button tech-button--primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增行业数据
        </el-button>
      </div>
    </dv-border-box-12>
    
    <!-- 筛选表单 -->
    <dv-border-box-8 class="tech-search-box">
      <div class="tech-search-bar">
        <el-form :inline="true" :model="filterForm" class="tech-search-form">
          <el-form-item label="行业名称">
            <el-input v-model="filterForm.industryName" placeholder="请输入行业名称" clearable />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="filterForm.enable" placeholder="全部" clearable class="datav-select">
              <el-option label="已启用" value="true" />
              <el-option label="已禁用" value="false" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="tech-button tech-button--primary" @click="handleSearch">
              <el-icon><Search /></el-icon>查询
            </el-button>
            <el-button class="tech-button" @click="resetFilter">
              <el-icon><Refresh /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </dv-border-box-8>
    
    <!-- 数据表格 -->
    <dv-border-box-10 class="tech-table-box">
      <div class="tech-table-container">
        <el-table
          v-loading="loading"
          :data="tableData"
          style="width: 100%"
          class="tech-table"
          element-loading-text="数据加载中..."
          element-loading-background="rgba(0, 20, 40, 0.8)"
        >
          <el-table-column prop="industryName" label="行业名称" min-width="120" />
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <el-tag
                :type="scope.row.enable !== false ? 'success' : 'info'"
                effect="dark"
                size="small"
              >
                {{ scope.row.enable !== false ? '已启用' : '已禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="行业图标" width="100">
            <template #default="scope">
              <el-image 
                v-if="scope.row.industryIcon" 
                :src="scope.row.iconUrl || scope.row.industryIcon" 
                style="width: 40px; height: 40px"
                fit="contain"
                class="industry-icon"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <div v-else class="image-error">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="职位信息" min-width="200">
            <template #default="scope">
              <div v-if="scope.row.positions && Object.keys(scope.row.positions).length > 0">
                <div v-for="(position, key) in scope.row.positions" :key="key" class="position-item">
                  <strong>{{ position.title }}</strong>: {{ position.description }}
                </div>
              </div>
              <span v-else>暂无职位信息</span>
            </template>
          </el-table-column>
          <el-table-column label="简历提示" min-width="200">
            <template #default="scope">
              <div v-if="scope.row.resumeTips && scope.row.resumeTips.length > 0">
                <el-tag 
                  v-for="(tip, index) in scope.row.resumeTips" 
                  :key="index" 
                  class="tip-item"
                  size="small"
                >
                  {{ tip }}
                </el-tag>
              </div>
              <span v-else>暂无简历提示</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" class="tech-button tech-button--primary" @click="handleEdit(scope.row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button type="danger" size="small" class="tech-button tech-button--danger" @click="handleDelete(scope.row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="tech-pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            prev-text="上一页"
            next-text="下一页"
            :pager-count="7"
          >
            <template #total>
              共 {{ total }} 条记录
            </template>
            <template #sizes>
              每页 {{ pageSize }} 条
            </template>
          </el-pagination>
        </div>
      </div>
    </dv-border-box-10>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete, Picture } from '@element-plus/icons-vue'
import { app, ensureLogin } from '../../utils/cloudbase'

export default {
  name: 'IndustryDataManagement',
  components: {
    Plus,
    Search,
    Refresh,
    Edit,
    Delete,
    Picture
  },
  setup() {
    const router = useRouter()
    
    // 数据加载状态
    const loading = ref(false)
    
    // 表格数据
    const tableData = ref([])
    
    // 分页相关
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    
    // 筛选表单
    const filterForm = reactive({
      industryName: '',
      enable: ''
    })
    
    // 获取行业数据
    const fetchIndustryData = async () => {
      loading.value = true
      try {
        // 确保用户已登录
        await ensureLogin()
        
        // 构建筛选条件
        const filterData = {
          page: currentPage.value,
          pageSize: pageSize.value
        }
        
        // 添加可选的筛选条件
        if (filterForm.industryName) filterData.industryName = filterForm.industryName
        if (filterForm.enable !== '') filterData.enable = filterForm.enable === 'true'
        
        // 调用云函数
        let res;
        try {
          res = await app.callFunction({
            name: 'admin-industry-data-crud',
            data: {
              action: 'list',
              data: filterData
            }
          });
        } catch (callError) {
          console.error('调用云函数失败:', callError);
          res = { result: { code: -1, message: '调用云函数失败' } };
        }
        
        const result = res.result || {}
        
        if (result.code === 0) {
          tableData.value = result.data.list || []
          total.value = result.data.total || 0
          
          // 预处理图片URL
          processImageUrls();
        } else {
          ElMessage.error(result.message || '获取行业数据失败')
          tableData.value = []
          total.value = 0
        }
      } catch (error) {
        console.error('获取行业数据出错:', error)
        ElMessage.error('获取行业数据出错: ' + error.message)
        tableData.value = []
        total.value = 0
      } finally {
        loading.value = false
      }
    }
    
    // 处理查询
    const handleSearch = () => {
      currentPage.value = 1
      fetchIndustryData()
    }
    
    // 重置筛选条件
    const resetFilter = () => {
      filterForm.industryName = ''
      filterForm.enable = ''
      handleSearch()
    }
    
    // 处理页码变化
    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchIndustryData()
    }
    
    // 处理每页条数变化
    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
      fetchIndustryData()
    }
    
    // 处理新增行业数据
    const handleAdd = () => {
      router.push('/industry-data/add')
    }
    
    // 处理编辑行业数据
    const handleEdit = (row) => {
      if (row && row._id) {
        router.push(`/industry-data/edit/${row._id}`)
      } else {
        ElMessage.error('无效的行业数据ID')
      }
    }
    
    // 处理删除行业数据
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要删除行业 "${row.industryName}" 的数据吗？此操作不可恢复。`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          customClass: 'tech-message-box'
        }
      ).then(async () => {
        loading.value = true
        try {
          // 确保用户已登录
          await ensureLogin()
          
          // 调用云函数
          const res = await app.callFunction({
            name: 'admin-industry-data-crud',
            data: {
              action: 'delete',
              data: { _id: row._id }
            }
          })
          
          const result = res.result || {}
          
          if (result.code === 0) {
            ElMessage.success('删除成功')
            fetchIndustryData() // 重新加载数据
          } else {
            ElMessage.error(result.message || '删除失败')
          }
        } catch (error) {
          console.error('删除行业数据出错:', error)
          ElMessage.error('删除行业数据出错: ' + error.message)
        } finally {
          loading.value = false
        }
      }).catch(() => {
        // 用户取消删除操作
      })
    }
    
    // 处理图片URL
    const processImageUrls = async () => {
      if (!tableData.value || tableData.value.length === 0) return;
      
      // 收集所有需要处理的图片路径
      const iconPaths = tableData.value
        .filter(item => item.industryIcon && item.industryIcon.startsWith('cloud://'))
        .map(item => item.industryIcon);
      
      if (iconPaths.length === 0) return;
      
      try {
        // 批量获取临时URL
        const tempFileRes = await app.getTempFileURL({
          fileList: iconPaths
        });
        
        if (tempFileRes.fileList && tempFileRes.fileList.length > 0) {
          // 更新表格数据中的图片URL
          tempFileRes.fileList.forEach(file => {
            const item = tableData.value.find(item => item.industryIcon === file.fileID);
            if (item) {
              item.iconUrl = file.tempFileURL;
            }
          });
        }
      } catch (error) {
        console.error('批量获取图片URL失败:', error);
      }
    }
    
    
    // 组件挂载时获取数据
    onMounted(() => {
      fetchIndustryData()
    })
    
    return {
      loading,
      tableData,
      currentPage,
      pageSize,
      total,
      filterForm,
      handleSearch,
      resetFilter,
      handleCurrentChange,
      handleSizeChange,
      handleAdd,
      handleEdit,
      handleDelete,
      processImageUrls
    }
  }
}
</script>

<style>
/* 全局样式覆盖 */
.el-select .el-input__wrapper {
  background-color: rgba(0, 30, 60, 0.6) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  box-shadow: none !important;
}

.el-select .el-input__inner {
  color: #ffffff !important;
}

.el-select-dropdown {
  background-color: rgba(0, 30, 60, 0.9) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
}

.el-select-dropdown__item {
  color: #ffffff !important;
}

.el-select-dropdown__item.hover, 
.el-select-dropdown__item:hover {
  background-color: rgba(0, 192, 255, 0.2) !important;
}

.el-select-dropdown__item.selected {
  background-color: rgba(0, 192, 255, 0.4) !important;
  color: #00c0ff !important;
}
</style>

<style scoped>
.industry-data-management {
  padding: 0;
}

.position-item {
  margin-bottom: 5px;
  font-size: 14px;
  color: #ffffff;
  text-shadow: 0 0 5px rgba(0, 192, 255, 0.5);
}

.tip-item {
  margin-right: 5px;
  margin-bottom: 5px;
  background-color: rgba(0, 30, 60, 0.6);
  border-color: rgba(0, 192, 255, 0.5);
  color: #ffffff;
}

.image-error {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 40px;
  height: 40px;
  background-color: rgba(0, 30, 60, 0.4);
  color: #00c0ff;
  font-size: 20px;
  border: 1px solid rgba(0, 192, 255, 0.3);
  border-radius: 4px;
  box-shadow: 0 0 10px rgba(0, 192, 255, 0.2);
}

.industry-icon {
  border: 2px solid rgba(0, 192, 255, 0.5);
  border-radius: 4px;
  box-shadow: 0 0 15px rgba(0, 192, 255, 0.3);
  transition: all 0.3s;
}

.industry-icon:hover {
  transform: scale(1.05);
  box-shadow: 0 0 20px rgba(0, 192, 255, 0.5);
}

/* Datav风格的表单元素 */
.datav-select {
  width: 120px;
}

:deep(.el-form-item__label) {
  color: #00c0ff !important;
}

:deep(.el-input__wrapper) {
  background-color: rgba(0, 30, 60, 0.6) !important;
  border: 1px solid rgba(0, 192, 255, 0.5) !important;
  box-shadow: none !important;
}

:deep(.el-input__inner) {
  color: #ffffff !important;
}
</style>
